﻿using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Microsoft.AspNetCore.TestHost;
using Newtonsoft.Json.Linq;
using Xunit.Abstractions;

// ReSharper disable MissingXmlDoc

namespace SwallowTestCommon {
    public static class HttpClientExtenstion {
        public static async Task<string> GetAccessTokenAsync(this HttpClient client, ITestOutputHelper output = null) {
            var url = "http://localhost:9142/api/account/login";
            var value = new {
                username = "18121629620",
                password = "Welcome123",
                rememberme = true
            };
            var responseMessage = await client.PostAsJsonAsync<object>(url, value);
            var result = await responseMessage.Content.ReadAsStringAsync();
            output.WriteLine(result);
            responseMessage.EnsureSuccessStatusCode();
            var r = JsonConvert.DeserializeObject<Rootobject>(result);
            return r.accessToken;
        }
        public static async Task<string> GetAccessTokenAsync(this TestServer server, ITestOutputHelper output = null) {
            var url = "http://localhost:9142/api/account/login";
            var value = new {
                username = "18121629620",
                password = "Welcome123",
                rememberme = true
            };
            var client = new HttpClient();
            var responseMessage = await client.PostAsJsonAsync<object>(url, value);
            var result = await responseMessage.Content.ReadAsStringAsync();
            output?.WriteLine(result);
            responseMessage.EnsureSuccessStatusCode();
            var r = JsonConvert.DeserializeObject<Rootobject>(result);
            return r.accessToken;
        }

        public static async Task<string> GetConnectToken(this TestServer server, ITestOutputHelper output = null) {
            dynamic _options = new {
                DefaultClientId = "default",
                DefaultScope = "default",
                DefaultClientSecret = "secret",
                CodeSmsTemplate = "59680"
            };
            //var client = server.CreateClient();
            var client = new HttpClient();
            var endpoint = $"http://localhost:9141/connect/token";
            var clientId = _options.DefaultClientId;
            var clientSecret = _options.DefaultClientSecret;
            var scope = _options.DefaultScope;
            client.DefaultRequestHeaders.TryAddWithoutValidation("clientId", clientId);
            client.DefaultRequestHeaders.TryAddWithoutValidation("clientSecret", clientSecret);
            client.DefaultRequestHeaders.TryAddWithoutValidation("scope", scope);
            client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(clientId, clientSecret);
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("grant_type","password"),
                new KeyValuePair<string, string>("username","18121629620"),
                new KeyValuePair<string, string>("password","Welcome123"),
                new KeyValuePair<string, string>("scope",scope),
            });
            var response = await client.PostAsync(endpoint, content);
            var message = await response.Content.ReadAsStringAsync();
            output?.WriteLine("{0},{1}", response.StatusCode, message);
            response.EnsureSuccessStatusCode();
            dynamic result = JObject.Parse(message);
            return (string)result.access_token;
        }
        public class Rootobject {
            public string accessToken { get; set; }
            public int expiresIn { get; set; }
            public string raw { get; set; }
            public string refreshToken { get; set; }
            public string tokenType { get; set; }
            public bool isError { get; set; }
            public string error { get; set; }
        }
    }
}
